package com.zzw.aliyun.green.service;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.aliyun.green20220302.models.DescribeImageModerationResultResponse;
import com.aliyun.green20220302.models.ImageAsyncModerationResponse;
import com.aliyun.green20220302.models.ImageModerationResponse;
import com.aliyun.tea.TeaException;
import com.zzw.aliyun.green.common.exception.AliyunGreenException;
import com.zzw.aliyun.green.config.AliyunGreenConfigProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Getter
@Setter
@Slf4j
@Component
public class GreenImageScanNew {

    @Autowired
    private com.aliyun.green20220302.Client client;

    /**
     * 增强版green图片扫描
     *
     * @param image
     * @return  pass表示审核通过
     * @throws Exception
     */
    public Map imageScan(String image) throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html
        com.aliyun.green20220302.models.ImageModerationRequest imageModerationRequest = new com.aliyun.green20220302.models.ImageModerationRequest();
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

        //设置要检测的场景
        imageModerationRequest.setService("baselineCheck");

        cn.hutool.json.JSONObject tasks = new cn.hutool.json.JSONObject();
        tasks.set("imageUrl", image);
        tasks.set("dataId", "img1");
        imageModerationRequest.setServiceParameters(tasks.toString());

        ImageModerationResponse response = null;
        try {
            response = client.imageModerationWithOptions(imageModerationRequest, runtime);
        } catch (TeaException error) {
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
            throw new AliyunGreenException(error.getMessage());
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
            throw new AliyunGreenException(error.getMessage());
        }

        Map<String, String> resultMap = new HashMap<>();

        //服务端接收到请求，并完成处理返回的结果
        if (response != null && response.getStatusCode() == 200) {
            JSONObject responseJson = new JSONObject(response);
            JSONObject body = responseJson.get("body", JSONObject.class);
            if (body != null && "200".equals(body.get("code", String.class))) {
                //图片处理结果
                JSONObject data = body.get("data", JSONObject.class);
                resultMap.put("status", "1");
                if (data != null) {
                    String dataId = data.get("dataId", String.class);
                    String result = "";
                    JSONArray jsonArray = data.get("result", JSONArray.class);
                    for (Object item : jsonArray) {
                        JSONObject itemJson = new JSONObject(item);
                        String label = itemJson.get("label", String.class);
                        result = result + label;
                    }
                    //result = nonLabel  合规
                    if ("nonLabel".equals(result)) {
                        resultMap.put("suggestion", "pass");
                        return resultMap;
                    }
                    // 否则 不合规
                    resultMap.put("suggestion", result);
                    resultMap.put("label", dataId);
                    return resultMap;
                }
            } else {
                /**
                 * 表明请求整体处理失败，原因视具体的情况详细分析
                 */
                System.out.println("the whole image scan request failed. response:" + new JSONObject(response));
                resultMap.put("status", "0");
                return resultMap;
            }
        }
        resultMap.put("status", "0");
        return resultMap;
    }


    /*
        图片检测增强版支持的检测服务。取值：
        baselineCheck：通用基线检测
        baselineCheck_pro：通用基线检测_专业版
        baselineCheck_cb：通用基线检测_海外版
        tonalityImprove：内容治理检测
        aigcCheck：AIGC 图片检测
        profilePhotoCheck：头像图片检测
        advertisingCheck：营销素材检测
        liveStreamCheck：视频\直播截图检测
     */

    /**
     * 提交图片扫描异步请求，返回reqId
     * 用于获取异步结果
     *
     * @param image
     * @return
     */
    public Map imageScanSubmitAsync(String image) {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html
        com.aliyun.green20220302.models.ImageAsyncModerationRequest imageAsyncModerationRequest = new com.aliyun.green20220302.models.ImageAsyncModerationRequest();
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

        //设置要检测的场景
        imageAsyncModerationRequest.setService("baselineCheck");

        cn.hutool.json.JSONObject tasks = new cn.hutool.json.JSONObject();
        tasks.set("imageUrl", image);
        tasks.set("dataId", "");
        imageAsyncModerationRequest.setServiceParameters(tasks.toString());
        ImageAsyncModerationResponse response = null;
        try {
            response = client.imageAsyncModerationWithOptions(imageAsyncModerationRequest, runtime);
        } catch (TeaException error) {
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
            throw new AliyunGreenException(error.getMessage());
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
            throw new AliyunGreenException(error.getMessage());
        }

        Map<String, String> resultMap = new HashMap<>();

        //服务端接收到请求，并完成处理返回的结果
        if (response != null && response.getStatusCode() == 200) {
            JSONObject responseJson = new JSONObject(response);
            JSONObject body = responseJson.get("body", JSONObject.class);
            if (body != null && "200".equals(body.get("code", String.class))) {
                //图片处理结果
                JSONObject data = body.get("data", JSONObject.class);
                if (data != null) {
                    String dataId = data.get("dataId", String.class);
                    String reqId = data.get("reqId", String.class);

                    resultMap.put("status", "1");
                    resultMap.put("reqId", reqId);
                    resultMap.put("dataId", dataId);
                    return resultMap;
                }
            } else {
                /**
                 * 表明请求整体处理失败，原因视具体的情况详细分析
                 */
                System.out.println("the whole image scan request failed. response:" + new JSONObject(response));
                resultMap.put("status", "0");
                return resultMap;
            }
        }
        resultMap.put("status", "0");
        return resultMap;
    }


    /**
     * 获取异步审核结果
     * @param reqId
     * @return
     */
    public Map imageScanGetResult(String reqId) {
        com.aliyun.green20220302.models.DescribeImageModerationResultRequest describeImageModerationResultRequest = new com.aliyun.green20220302.models.DescribeImageModerationResultRequest();
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

        //设置要检测的场景
        describeImageModerationResultRequest.setReqId(reqId);

        DescribeImageModerationResultResponse response = null;
        try {
            // 复制代码运行请自行打印 API 的返回值
            response = client.describeImageModerationResultWithOptions(describeImageModerationResultRequest, runtime);
        } catch (TeaException error) {
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
            throw new AliyunGreenException(error.getMessage());
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
            throw new AliyunGreenException(error.getMessage());
        }

        //解析结果
        Map<String, String> resultMap = new HashMap<>();

        //服务端接收到请求，并完成处理返回的结果
        if (response != null && response.getStatusCode() == 200) {
            JSONObject responseJson = new JSONObject(response);
            JSONObject body = responseJson.get("body", JSONObject.class);
            if (body != null && "200".equals(body.get("code", String.class))) {
                //图片处理结果
                JSONObject data = body.get("data", JSONObject.class);
                if (data != null && reqId.equals(data.get("reqId", String.class))) {
                    JSONArray frames = data.get("frame", JSONArray.class);
                    for (Object frame : frames) {
                        JSONObject frameJSON = new JSONObject(frame);
                        String jsonString = frameJSON.toString();
                        JSONArray results = frameJSON.get("Result", JSONArray.class);
                        for (Object result : results) {
                            JSONObject entries = new JSONObject(result);
                            String label = entries.get("Label", String.class);
                            if ("nonLabel".equals(label)){
                                //审核通过
                                resultMap.put("suggestion", "pass");
                            }
                        }
                    }
                    resultMap.put("status", "1");
                    return resultMap;
                }
            } else {
                /**
                 * 表明请求整体处理失败，原因视具体的情况详细分析
                 */
                System.out.println("the whole image scan request failed. response:" + new JSONObject(response));
                resultMap.put("status", "0");
                return resultMap;
            }
        }
        resultMap.put("status", "0");
        return resultMap;

    }


}